package com.wangyadong.hobby.metric.counter.lession7;

import com.codahale.metrics.ConsoleReporter;
import com.codahale.metrics.Counter;
import com.codahale.metrics.MetricRegistry;

import java.sql.Time;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *
 * @author <714037465@qq.com>
 * @since 2018/12/1818:06
 **/
public class CounterExample {

    private static MetricRegistry registry = new MetricRegistry();

    /***block queue**/
    private static final BlockingDeque queue = new LinkedBlockingDeque(1_000);

    private static ConsoleReporter reporter = ConsoleReporter.forRegistry(registry)
            .convertRatesTo(TimeUnit.SECONDS)
            .convertDurationsTo(TimeUnit.SECONDS)
            .build();


    public static void main(String[] args) {
        reporter.start(10, TimeUnit.SECONDS);
        Counter counter=registry.counter("queue-count", () -> new Counter());
        new Thread(() -> {

            while (true) {
                randomSleep();
                queue.add(System.nanoTime());
                counter.inc();
            }

        }).start();
        ///////////////////////////////////////////////////////////////////////////////////////
        new Thread(() -> {

            while (true) {
                randomSleep();
               if(queue.poll()!=null){
                   counter.dec();
               }

            }

        }).start();
    }

    private static void randomSleep() {
        try {
            TimeUnit.MILLISECONDS.sleep(ThreadLocalRandom.current().nextInt(500));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
